﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LitJson;

[AddComponentMenu("PUEX/Emitter/BoxEmitter")]
public class PUEXBoxEmitter : PUEXEmitter {

	#region - Editable property
	[Header("BoxEmitter:")]
	public Vector3 size;
	public float directionAngle;
	public bool emitLinear;
	public bool flipLinear;
	public bool alignDirection;
	public float randomDeviant;
	#endregion
	
	#region - Lifecycle
	public PUEXBoxEmitter ()
	{
		size = new Vector3 (20f, 20f, 20f);
		directionAngle = 0f;
		emitLinear = false;
		flipLinear = false;
		alignDirection = true;
		randomDeviant = 0f;
	}
	#endregion

	#region - Emit
	protected override void initParticlePosition (PUEXParticle particle, int index, int requested)
	{
		if (emitLinear) {
			float z = -size.z * 0.5f + timeFraction * size.z;
			if (flipLinear)
				z = -size.z * 0.5f + (1f - timeFraction) * size.z;
			float x = -size.x * 0.5f + ((float)index + 0.5f) / (float)requested * size.x;
			float y = size.y * 0.5f * Random.Range (-1f, 1f);
			particle.position = particle.originalPosition = emitterToSimulationTransform.MultiplyPoint (new Vector3(x, y, z));
		} else {
			Vector3 offset = new Vector3 (size.x * 0.5f * Random.Range (-1f, 1f), size.y * 0.5f * Random.Range (-1f, 1f), size.z * 0.5f * Random.Range (-1f, 1f));
			particle.position = particle.originalPosition = emitterToSimulationTransform.MultiplyPoint (offset);
		}
	}
	
	protected override void initParticleVelocity (PUEXParticle particle, int index, int requested)
	{
		if (alignDirection) {
			Vector3 dir = Vector3.forward;
			
			if (directionAngle > 0f) {
				Vector3 pAxis = Vector3.Cross(dir, Vector3.up);
				dir = Quaternion.AngleAxis(directionAngle, pAxis) * dir;
			}
			
			if (randomDeviant > 0f) {
				dir = PUEXUtils.randomDeviant(dir, randomDeviant);
			}
			
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (dir).normalized;
		} else {
			particle.direction = particle.originalDirection = emitterToSimulationTransform.MultiplyVector (Random.insideUnitSphere).normalized;
		}

		particle.speed = particle.originalSpeed = startSpeed.getValue (timeFraction);
	}
	#endregion
	
	#region - Draw
	public void OnDrawGizmos()
	{
		if (!enabled)
			return;
		
		Matrix4x4 defaultMatrix = Gizmos.matrix;
		Gizmos.matrix = transform.localToWorldMatrix;
		
		Color defaultColor = Gizmos.color;
		Gizmos.color = Color.blue;

		Gizmos.DrawWireCube (Vector3.zero, size);
		
		Gizmos.color = defaultColor;
		Gizmos.matrix = defaultMatrix;
	}
	#endregion

	#region - Serialization
	public override JsonData save (JsonData systemData)
	{
		JsonData ret = base.save (systemData);

		ret ["size"] = PUEXUtils.serializeVector3(size);
		ret ["direction_angle"] = directionAngle;
		ret ["emit_linear"] = emitLinear;
		ret ["flip_linear"] = flipLinear;
		ret ["align_direction"] = alignDirection;
		ret ["random_deviant"] = randomDeviant;
		
		return ret;
	}
	#endregion

}
